package com.hw.utils.forkjoinpool;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.ForkJoinTask;
import java.util.concurrent.TimeUnit;

/**
 * @program: hwUtils
 * @description:
 * @author: hewei
 * @date: 2023-03-16 10:46
 **/
public class ForkJoinPoolDemo {

    public static void main(String[] args) throws InterruptedException, ExecutionException {

        /***************************************一、无返回值************************************/

        System.out.println("----------------------------RecursiveAction----------------------------");
        /*创建没有返回值的任务*/
        RecursiveActionWorker actionWorker=new RecursiveActionWorker(0,100);

        /*创建ForkJoinPool 线程池*/
//        ForkJoinPool forkJoinPool= new ForkJoinPool(Runtime.getRuntime().availableProcessors());
        ForkJoinPool actionForkJoinPool= new ForkJoinPool(4);

        /*使用线程池进行任务的分解执行*/
        actionForkJoinPool.submit(actionWorker);

        /*阻塞 3 秒 直到线程池终止*/
        actionForkJoinPool.awaitTermination(2, TimeUnit.SECONDS);

        /*关闭线程池*/
        actionForkJoinPool.shutdown();

        /*************************************二、有返回值************************************/
        System.out.println("----------------------------RecursiveTask----------------------------");

        /*创建有返回值的任务*/
        RecursiveTaskWorker taskWorker=new RecursiveTaskWorker(0,100);

        /*创建ForkJoinPool 线程池*/
        ForkJoinPool taskForkJoinPool= new ForkJoinPool(4);

        /*使用线程池进行任务的分解执行*/
        ForkJoinTask<Integer> task=taskForkJoinPool.submit(taskWorker);

        /*获取数据 直到线程池终止*/
        System.out.println("ForkJoinPool有返回值的汇总计算结果："+task.get());
        /*关闭线程池*/
        taskForkJoinPool.shutdown();

        int sum=0;
        for (int i = 0; i < 100; i++) {
            sum+=i;
        }
        System.out.println("循环计算结果："+sum);
    }
}
